package com.suchbear.homeiot

import android.os.*
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*


class MainActivity : AppCompatActivity() {
    private val HANDLER_REFRESHUI: Int = 0x11;

    private lateinit var udpClient: UDPClient
    private var sendTag: Boolean = true

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        initData()
    }

    private val handler = Handler(Looper.getMainLooper()) {
        when (it.what) {
            HANDLER_REFRESHUI -> tv_tempC.text = (it.obj).toString()
        }
        false
    }

    private fun initData() {
        udpClient = UDPClient(object : ReceiveMessageListener {
            override fun onMessage(message: String) {
                val msg = Message()
                msg.what = HANDLER_REFRESHUI
                msg.obj = message
                handler.sendMessage(msg)
            }
        })
        val udpThread = Thread(udpClient)
        udpThread.start()

        val sendThread = Thread(Runnable {
            while (sendTag) {
                if (::udpClient.isInitialized) {
                    udpClient.send("ask")
                }
                try {
                    Thread.sleep(1000)
                } catch (e: InternalError) {
                    e.printStackTrace()
                }
            }
        })
        sendThread.start()
    }

    override fun onDestroy() {
        super.onDestroy()
        sendTag = false
        if (udpClient.isUdpLife()) {
            udpClient.setUdpLife(false)
        }
    }
}